package com.book.app.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.book.app.aop.SystemControllerLog;
import com.book.app.entity.Users;
import com.book.app.service.UsersService;
import com.book.app.tools.CommonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "用户模块")
@RestController
@RequestMapping("user")
@CrossOrigin //前后端分离配置跨域访问
public class UsersController  {

    @Resource
    private UsersService usersService;

    @ApiOperation("改变用户状态操作")
    @SystemControllerLog(description ="改变用户状态操作")
    @PostMapping("/changeStats")
    public CommonResult changeStats(@RequestBody Users users){
        if(users.getStats()==0){
            users.setStats(1);//禁用
        }else if(users.getStats()==1){
            users.setStats(0);//启用
        }
        boolean flag=usersService.updateById(users);
        if(flag){
            return CommonResult.success(flag);
        }
        return CommonResult.failed();
    }


    @ApiOperation("分页查询用户信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page",value = "分页起始数据",required = true,
                    example = "1"),
            @ApiImplicitParam(name = "limit",value = "每页显示分页最大数据",required = true,
                    example = "10"),
            @ApiImplicitParam(name = "uname",value = "用户名称查询",example = "张三"),
    })
    @SystemControllerLog(description ="用户分页查询信息")
    @GetMapping("/findPager")
    public CommonResult findPager(Integer page, Integer limit, String uname){
       //谁登录成功后显示当前登录用户信息，而不是所有信息
        QueryWrapper<Users> queryWrapper=new QueryWrapper<>();
        if(!"".equals(uname)&&uname!=null){
            queryWrapper.like(true,"uname",uname);
        }
        queryWrapper.ne("uname","admin");
        Map<String,Object> map=new HashMap<>();
        map.put("page",page);
        map.put("count",usersService.count(queryWrapper));
        map.put("data",usersService.page(new Page<Users>(page,limit),queryWrapper).getRecords());
        return CommonResult.success(map);
    }
    @ApiOperation("添加用户信息")
    @SystemControllerLog(description ="添加用户信息")
    @PostMapping("/save")
    public  CommonResult save(@RequestBody Users users){
        users.setCreatetime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        //将密码进行加密
        users.setPassword(new Md5Hash(users.getPassword(),users.getUname()+users.getPassword(),1000).toString());
        boolean flag= usersService.save(users);
        return flag?CommonResult.success(flag):CommonResult.failed();
    }

    @ApiOperation("批量删除用户信息")
    @SystemControllerLog(description ="批量删除用户信息")
    @PostMapping("/removeBatch")
    public  CommonResult removeBatch(@RequestParam("uids[]") List<Integer> uids){
        boolean flag= usersService.removeByIds(uids);
        return flag?CommonResult.success(flag):CommonResult.failed();
    }

    @ApiOperation("根据ID删除用户信息")
    @SystemControllerLog(description ="根据ID删除用户信息")
    @PostMapping("/remove")
    public  CommonResult removeBatch(@RequestParam("uid") Integer uid){
        boolean flag= usersService.removeById(uid);
        return flag?CommonResult.success(flag):CommonResult.failed();
    }


    @ApiOperation("修改用户信息")
    @SystemControllerLog(description ="修改用户信息")
    @PostMapping("/update")
       public  CommonResult update(@RequestBody Users users){
        users.setModifytime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        boolean flag= usersService.updateById(users);
        return flag?CommonResult.success(flag):CommonResult.failed();
    }

    @ApiOperation("登录")
    @SystemControllerLog(description ="登录")
    @GetMapping("/login")
    public CommonResult login(String username,String password){
        try {
            //加密验证
            UsernamePasswordToken token=new UsernamePasswordToken(username,
                    password);
            Subject subject= SecurityUtils.getSubject();
            if(!subject.isAuthenticated()){
                subject.login(token);//该方法是shiro提供的登录方法，该方法会自动跳转到用户定义的Realm中
            }
        }catch (AuthenticationException uae) {
            System.out.println("用户名称或者密码不正确");
            return  CommonResult.failed();
        }
        return CommonResult.success(username);//登录成功返回username

    }


    @ApiOperation("用户注销")
    @GetMapping("/logout")
    public CommonResult logout(){
        SecurityUtils.getSubject().logout();
        return CommonResult.success(200);
    }


}



